

#include <string.h>
#include "xDLPS.h"
#include "platform_utils.h"
#include "log.h"

#include "../module/hub.c"
#define LOG     xLOG_INFO0
#define LOG1    xLOG_INFO1 
#define LOG2    xLOG_INFO2 
#define DRIVER_MODULE_NUMS      0x10

T_IO_MODULE_CBS    *driver_modules[DRIVER_MODULE_NUMS];
uint8_t             m_hub_task_count;
extern bool uart_test_check_dlps_allowed(void);

volatile uint32_t dlps_flag = 0;


uint32_t xDLPS_register( const T_IO_MODULE_CBS* mod )
{
    for(int i = 0 ; i < m_hub_task_count; i ++ )
    {
        if( driver_modules[i] == mod )
        {
            return i; 
        }
    }
    
    uint32_t no = m_hub_task_count;
    driver_modules[ m_hub_task_count ++] = (T_IO_MODULE_CBS*)mod;
    LOG1("[DLPS]: %d tasks is registered\r\n", m_hub_task_count );
    
    return no; 
}

void xDLPS_Init(void)
{
    m_hub_task_count = 0;
    memset( &driver_modules,0, sizeof(driver_modules ) );

    hub_init_dlps();
}

void xDLPS_enter(void)
{
    LOG("[DLPS]: enter");
    for(uint8_t i = 0; i < m_hub_task_count; i ++)
    {
        if( driver_modules[i]->enter_dlps != NULL )
        {
            driver_modules[i]->enter_dlps();
        }
    }
}
void xDLPS_exit(void)
{
    for(uint8_t i = 0; i < m_hub_task_count; i ++)
    {
        if( driver_modules[i]->exit_dlps != NULL )
        {
            driver_modules[i]->exit_dlps();
        }
    }
    LOG("[DLPS]: exit");
}
bool xDLPS_check(void)
{
    return dlps_flag == 0 && uart_test_check_dlps_allowed();
}

inline void xDLPS_set(uint32_t flag)
{
    dlps_flag |= (1 << flag);
    LOG2("DLPS: after (%b) set flag =!!! %08X !!!\r\n", TRACE_STRING(driver_modules[flag]->name), dlps_flag );
}

inline void xDLPS_reset(uint32_t flag)
{
    dlps_flag &= ~(1 << flag);
    LOG2("DLPS: after (%b) reset flag =!!! %08X !!!\r\n", TRACE_STRING(driver_modules[flag]->name),dlps_flag );
    if(0 == dlps_flag)
    {
        platform_delay_ms(10);
    }
}


